package top.zhouze.common.data;

import android.content.Context;
import androidx.annotation.NonNull;
import androidx.room.Room;
import androidx.room.RoomDatabase;
import com.google.gson.GsonBuilder;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import top.zhouze.common.util.ReflectUtil;

import java.lang.reflect.ParameterizedType;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

public abstract class BaseRemoteRepository<A> {
    /**
     * 缓存 Retrofit Service
     */
    private final Map<String,Object> mRetrofitServiceCache = new HashMap<>();

    protected abstract Context getContext();

    protected void put(Class<?> clazz,String baseUrl,Interceptor... interceptor) {
        mRetrofitServiceCache.put(clazz.getSimpleName(),getRetrofit(baseUrl,interceptor).create(clazz));
    }

    protected void addService(Class<?> clazz,Retrofit retrofit) {
        mRetrofitServiceCache.put(clazz.getSimpleName(),retrofit);
    }

    protected Class<A> getDefaultApiClass() {
        return ReflectUtil.getGenericClass(this,0);
    }

    @SuppressWarnings("unchecked")
    public <T> T getService(@NonNull Class<T> service) {
        return (T)mRetrofitServiceCache.get(service.getSimpleName());
    }

    public A getDefaultService() {
        return getService(getDefaultApiClass());
    }

    private static Retrofit getRetrofit(String baseUrl,Interceptor... interceptors) {
        OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
        for (Interceptor interceptor: interceptors) {
            httpClient.addInterceptor(interceptor);
        }
        httpClient
                .connectTimeout(60, TimeUnit.SECONDS)
                .writeTimeout(60, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS);
        OkHttpClient client = httpClient.build();

        return new Retrofit
                .Builder()
                .baseUrl(baseUrl)
                .client(client)
                .addConverterFactory(GsonConverterFactory.create(new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create()))
                .addCallAdapterFactory(RxJava2CallAdapterFactory.createAsync())
                .build();
    }
}
